// 坐标取地址
function getAddressName(lng, lat) {
  var dfd = $.Deferred()
  AMap.service('AMap.Geocoder', function () {
    geocoder = new AMap.Geocoder({
      city: "010"//城市，默认：“全国”
    });
    var lnglatXY = [lng, lat];//关联的坐标
    geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        dfd.resolve(result.regeocode.formattedAddress);
      } else {
        dfd.resolve('未找到有效地址');
      }
    });
  })

 return dfd.promise();
}

(function (window, $, undefined) {
  'use strict';

  var dictData = {
    bookModel:{   //用车类型
      '1': '舒适型',
      '2': '商务7座',
      '3': '豪华轿车'
    },
    orderChannel: { //订单来源
      '1': '小程序',
      '2': '管理后台',
      '3': 'iOS',
      '4': '安卓'
    },
    orderType: {  //服务类型
      '1': '立即接机',
      '2': '立即接站',
      '3': '预约接机',
      '4': '预约接站',
      '5': '预约送机',
      '6': '预约送站',
      '7': '预约用车',
      '8': '立即用车',
      '9': '预约接机',
      '10': '预约接站'
    },
    state:{
      '0': '离线',
      '1': '上线',
      '2': '待命',
      '3': '入栈中',
      '4': '入栈',
      '5': '服务中'
    }

  };
  var cityData = {};
  var orderData = {};

  main(function () {
    //获取操作人并修改
    $("span[data-operator]").text(oUser.account)

    var $tableManual = $('#table-manual');
    util.jqGrid($tableManual, {
      url: ajaxURL.SCHEDULE + '/v1/schedule/record/list',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      shrinkToFit: false,
      colModel: [
        {
          label: '订单编号', key: true,name: 'order_no', width: 150, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.order_no + '">' + v + '</a>';
          }
        },
        { label: '创建时间', name: 'create_time', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '用车时间', name: 'plan_depart_time', width: 150, formatter: function (v) {
          return util.dateFormat(v);
        } },
        { label: '预估价', name: 'plan_price', width: 100, formatter: function (v) {
          return v / 100 + ' 元';
        } },
        { label: '下单人', name: 'placing_user_phone', width: 150 },
        { label: '用车人', name: 'passenger_phone', width: 150 },
        { label: '城市', name: 'city_id', width: 80, formatter: function (v) {
          return cityData[v] || '';
        } },
        {
          label: '服务类型', name: 'order_type', width: 80, formatter: function (v) {
          return dictData.orderType[v] || '';
        } },
        {
          label: '用车类型', name: 'auto_type', width: 80, formatter: function (v) {
          return dictData.bookModel[v] || '';
        } },
        { label: '失败时间', name: 'latest_schedule_time', width: 200 , formatter: function (v) {
          return util.dateFormat(v);
        }},
        { label: '订单来源', name: 'order_channel', width: 100, formatter: function (v) {
          return dictData.orderChannel[v] || '';
        } }
      ],
      loadComplete: function (res) {
        orderData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            orderData[item.order_no] = item;
          });
        }
      },
      pager: '#pager-manual'
    });

    var $tableDispatch = $('#table-manual-dispatch');
    util.jqGrid($tableDispatch, {
        url: ajaxURL.ORGANIZATION + '/driver/getDriverList',
        autowidth: true,
        height: $(window).height() - 350,
        multiselect: true,
        multiboxonly: true,
        shrinkToFit: false,
        colModel: [
          { name: 'kid', key: true, hidden: true },
          { label: '司机ID', name: 'kid', width: 50 },
          { label: '司机姓名', name: 'name', width: 100 },
          { label: '车牌号', name: 'autoNo', width: 100 },
          { label: '司机电话', name: 'phone', width: 150 },
          { label: '当前车辆定位', name: '_curPosition', width: 200 },
          // { label: '距上车地', name: '', width: 100 },
          { label: '司机状态', name: 'state', width: 80 ,formatter: function (v) {
            return dictData.state[v] || ''}
          }
        ],
        pager: '#pager-manual-dispatch',
        gridComplete: function() {
          var ids = $tableDispatch.jqGrid('getDataIDs');
          ids.forEach(function (id, index) {
            var rowData = $tableDispatch.jqGrid('getRowData', id)
            getAddressName(rowData.lng, rowData.lat).done(function(data) {
              $tableDispatch.jqGrid('setRowData', id, {
                _curPosition: data
              } )
            })
          });
        }
    });
    // 字典下拉数据
    util.selectHtml('[name="order_type"]', dictData.orderType, '', '', '请选择');
    util.selectHtml('[name="auto_type"]', dictData.bookModel, '', '', '请选择');
    util.selectHtml('[name="order_channel"]', dictData.orderChannel, '', '', '请选择');
    util.selectHtml('[name="city_id"]', cityData.city_id, '', '', '请选择');

    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="city_id"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        cityData[item.cityId] = item.name;
      });
      searchTable();
      // $("select option[value='4301']").attr("selected","selected").parent().attr('disabled','disabled');
      // $("select option[value='4301']").attr("selected","selected")
    });

    function searchTable() {
      var formData = util.formData('#form-search');

      var searchData = {
        order_no_like: formData.order_no_like,
        city_id: formData.city_id,
        placing_user_phone_like: formData.placing_user_phone_like,
        schedule_status: 108
      };

      if (formData.startDate) {
        searchData.create_time_begin = formData.startDate + 'T00:00:00+08:00'
       // util.getDate(formData.startDate + 'T00:00:00', 'YYYY-MM-ddThh:mm:ss+08:00');
      }
      if (formData.endDate) {
        searchData.create_time_end = formData.endDate + 'T23:59:59+08:00'
        // util.getDate(formData.endDate + 'T23:59:59', 'YYYY-MM-ddThh:mm:ss+08:00');
      }

      util.searchGrid($tableManual, searchData);
    }

    $('#search-btn').click(searchTable);

    // 创建时间段
    laydate.render({
      range: '至',
      elem: '#created-time',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#created-time').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 查看订单
    var $layerManualView = $('#layer-manual-view');
    $tableManual.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');
      // 根据 id 请求数据
      var data = orderData[id];

      data.plan_price = data.plan_price / 100 + ' 元';

      util.resetForm($layerManualView);

      $layerManualView.find('[data-operateTime]').text(util.dateFormat(data.create_time) || '');
      $layerManualView.find('[data-clientId]').text(id);

      var timestamp = Date.parse(new Date());
      // console.log(util.dateFormat(timestamp),util.dateFormat(data.latest_schedule_time))
      var shijianchuo = timestamp - data.latest_schedule_time;
      var second = shijianchuo/1000;

      function formatSeconds(value) {
        var theTime = parseInt(value);// 秒
        var theTime1 = 0;// 分
        var theTime2 = 0;// 小时
        if (theTime > 60) {
          theTime1 = parseInt(theTime / 60);
          theTime = parseInt(theTime % 60);
          if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
          }
        }
        var result = "" + parseInt(theTime) + "秒";
        if (theTime1 > 0) {
          result = "" + parseInt(theTime1) + "分" + result;
        }
        if (theTime2 > 0) {
          result = "" + parseInt(theTime2) + "小时" + result;
        }
        return result;
      }


      data.wait_time = formatSeconds(second);
      data.plan_depart_time = util.dateFormat(data.plan_depart_time);

      util.fillForm($layerManualView, data);

      util.layerOpen3({
        title: '订单详情',
        content: $('#layer-manual-view')
      });
    });

    // 手动派单
    $('#btn-dispatch').click(util.oneCheck($tableManual, function (id) {
      $tableDispatch.jqGrid('clearGridData');

      var $layerManualDispath = $('#layer-manual-dispatch');
      var $data = $.extend(true, {}, orderData[id]);

      $layerManualDispath.find(':input').removeAttr('disabled');

      $layerManualDispath.find('[data-clientid]').text(id);
      $layerManualDispath.find('[data-city]').text(cityData[$data.city_id]);
      $layerManualDispath.find('[data-serveType]').text(dictData.orderType[$data.order_type]);
      $layerManualDispath.find('[data-carType]').text(dictData.bookModel[$data.auto_type]);

      $layerManualDispath.find("select option[value='" + $data.city_id + "']").attr("selected", "selected").parent().attr('disabled', 'disabled');
      $layerManualDispath.find("select option[value='" + $data.auto_type + "']").attr("selected", "selected").parent().attr('disabled', 'disabled');


      util.layerOpen({
        title: false,
        content: $('#layer-manual-dispatch'),
        area: ['1000px', '']
      });
      util.tip.warn('请先选择改派司机类型进行搜索！')

      $('#driver-search').click();
    }));

    // 根据司机状态搜索查询司机列表
    $('#driver-search').off('click').click(function () {
      var searchData = util.formData($('#layer-manual-dispatch .d-content .form-row'));
      var sendState = "";
      if ($("input[type='checkbox']").is(':checked') === false) {
        util.tip.warn('请选择要改派的司机状态！');
        return;
      } else {
        for (var i = 0; i < searchData.state.length; i++) {
          sendState += searchData.state[i] + ','
        }
      }
      sendState = sendState.substring(0, sendState.length - 1)
      var newPostData = {
        cityId: searchData.city_id,
        autoTypeId: searchData.bookModel,
        stateIn: sendState
      };

      util.searchGrid($tableDispatch, newPostData);
    })

    //确认改派
    $('.submit').click(util.oneCheck($tableDispatch, function (id) {
      // var data = driverData[id];
      var id = Number(id);
      var orderNo = $('#layer-manual-dispatch').find('[data-clientId]').text();
      var postData = {
        order_no: orderNo,
        driver_id: id
      }
      layer.confirm('确定将此订单改派给选中司机？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.post(ajaxURL.SCHEDULE + '/v1/schedule/record/changeDriver', postData, function (res) {
          layer.closeAll();
          util.tip.success('改派成功');
          $tableManual.trigger('reloadGrid');
        });
      });
    }))

  });


})(window, jQuery);
